public class Solution23 {
    /**
     * 合并 k 个排序链表，返回合并后的排序链表。请分析和描述算法的复杂度。
     * 示例:
     * <p>
     * 输入:
     * [
     * 1->4->5,
     * 1->3->4,
     * 2->6
     * ]
     * 输出: 1->1->2->3->4->4->5->6
     */

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        if (lists.length == 1) return lists[0];
        ListNode head = mergeCore(lists, 0, lists.length - 1);
        return head;
    }

    public ListNode mergeCore(ListNode[] lists, int l, int r) {
        if (l == r) return lists[l];
        int mid = l + ((r - l) >> 1);
        ListNode left = mergeCore(lists, l, mid);
        ListNode right = mergeCore(lists, mid + 1, r);
        return merge(left, right);
    }

    public ListNode merge(ListNode l1, ListNode l2){
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        if (l1.val < l2.val) {
            l1.next = merge(l1.next, l2);
            return l1;
        }else {
            l2.next = merge(l1,l2.next);
            return l2;
        }
    }

}
